﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutomatedLab.Validator.FailoverCluster
{
    class DuplicateClusterIp : LabValidator, IValidate
    {
        public DuplicateClusterIp()
        {
            messageContainer = RunValidation();
        }

        public override IEnumerable<ValidationMessage> Validate()
        {
            var clusterToIp = new Dictionary<string, string>();

            foreach (var node in machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.FailoverNode)))
            {
                var tempNode = node.Roles.Where(r => r.Name.Equals(Roles.FailoverNode)).First();
                var clusterName = "ALCluster";
                if (tempNode.Properties.ContainsKey("ClusterName"))
                {
                    clusterName = tempNode.Properties["ClusterName"].ToString();
                }

                var clusterIp = "autogenerated";
                if (tempNode.Properties.ContainsKey("ClusterIp"))
                {
                    clusterIp = node.Roles.Where(r => r.Name.Equals(Roles.FailoverNode)).First().Properties["ClusterIp"].ToString();
                }

                if (!clusterToIp.ContainsKey(clusterName))
                {
                    clusterToIp.Add(clusterName, clusterIp);
                }

                clusterToIp[clusterName] = clusterIp;
            }

            foreach (var entry in clusterToIp)
            {
                foreach (var compareTo in clusterToIp)
                {
                    if (entry.Key.Equals(compareTo.Key)) continue;

                    if (!entry.Value.Equals(compareTo.Value)) continue;

                    yield return new ValidationMessage
                    {
                        Message = $"Duplicate cluster IP {entry.Value} found",
                        TargetObject = string.Join(", ", new List<string> { entry.Key, compareTo.Key }),
                        Type = MessageType.Error
                    };
                }
            }
        }
    }
}
